package com.king.edu.aop;

import org.apache.dubbo.rpc.RpcContext;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName: HttpAspect
 * @Description: HTTP AOP拦截
 * @Author: wangchangyong
 * @Date: 2020/06/08 20:34
 * @Version: 1.0.0
 */
@Aspect
@Configuration
public class HttpAspect {

    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    /**
     * 定义切点
     */
    @Pointcut(value = "execution(* com.king.edu.controller.*.*(..))")
    public void controllerAspect() {

    }

    @Around("controllerAspect()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String ipAddr = request.getRemoteAddr();

        StringBuffer sb = new StringBuffer();
        sb.append("className = " + proceedingJoinPoint.getTarget().getClass() +
                ", methodName = " + proceedingJoinPoint.getSignature().getName() +
                ", address = " + request.getRemoteAddr());
        logger.info("接受请求: {}",sb.toString());

        // 设置RpcContext
        RpcContext.getContext().setAttachment("requestIp", ipAddr);

        Object result = proceedingJoinPoint.proceed();
        return result;
    }
}
